package com.sooncode.project.focusservice._.base;

import com.sooncode.project.core.finder.Finder;
import com.sooncode.project.core.finder.Page;
import com.sooncode.project.core.model.DomainException;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public abstract class BaseService<T extends BaseDomainModel<T>> {
    protected Class<T> getType(){
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        Type[] typeArguments = superClass.getActualTypeArguments();
        return (Class<T>) typeArguments[0];
    }
    public boolean add(Map<String,Object> map){
        try {
            T model = getType().newInstance();
            model.add(map);
            return true;
        }catch(DomainException ex){
            throw ex;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            throw new DomainException("保存添加数据时异常");
        }
    }
    public boolean modify(String id,Map<String,Object> map){
        if(StringUtils.isEmpty(id))
            throw new DomainException("缺少数据id");
        try {
            T model=getById(id);
            model.modify(map);
            return true;
        }catch(DomainException ex){
        throw ex;
    }
        catch (Exception ex) {
        ex.printStackTrace();
        throw new DomainException("保存修改数据时异常");
    }

    }
    public boolean delete(String id){
        if(StringUtils.isEmpty(id))
            throw new DomainException("缺少数据id");
        T model=getById(id);
        model.delete();
        return true;
    }
    public Page<T> getPageList(int pageSize, int pageIndex, Map<String,Object> map) {
        return new Finder<T>(getType())
            .byMap(map)
            .page(pageSize, pageIndex);
    }
    public List<T> getList(Map map){
        return new Finder<T>(getType()).byMap(map).list();
    }
    public T getById(String id){
        if(StringUtils.isEmpty(id))
            throw new DomainException("缺少数据id");
        return new Finder<T>(getType()).byId(id);
    }

}
